package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.ShopCartBean;
import com.project.mapper.IShopCartMapper;
import com.project.service.IShopCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ShopCartServiceImpl implements IShopCartService {
    @Autowired
    private IShopCartMapper shopCartMapper;

    @Override
    public void add(Integer productId, Integer userId) {
        QueryWrapper<ShopCartBean> qw = new QueryWrapper<>();
        qw.eq("fk_productId",productId);
        qw.eq("fk_userId",userId);

        ShopCartBean shopCartBean = shopCartMapper.selectOne(qw);
        if (shopCartBean == null){
            shopCartBean = new ShopCartBean(userId,productId);
            shopCartMapper.insert(shopCartBean);
        }else {
            shopCartBean.setCount(shopCartBean.getCount()+1);
            shopCartMapper.updateById(shopCartBean);
        }
    }

    @Override
    public List<ShopCartBean> findAll(Integer userId) {
        return shopCartMapper.findByUser(userId);
    }

    @Override
    public void del(Integer cartId) {
        shopCartMapper.deleteById(cartId);
    }

    @Override
    public void updateCount(Integer cartId, Integer count) {
        ShopCartBean shopCartBean = shopCartMapper.selectById(cartId);
        shopCartBean.setId(cartId);
        shopCartBean.setCount(count);
        shopCartMapper.updateById(shopCartBean);
    }
}
